﻿using furion.blog.Application.RocketMQ.Producers;
using Furion;
using Furion.DependencyInjection;
using NewLife;
using NewLife.Log;
using NewLife.RocketMQ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Application.RocketMQ.Consumers
{
    /// <summary>
    /// 阿里云短信发送记录消费者
    /// </summary>
    public class AliSmsSendRecordConsumer : ISingleton
    {
        Consumer _consumer;
        string TOPIC = AliSmsSendRecordProducer.TOPIC;
        string GROUP = "ALI-SMS-SEND-RECORD-GROUPONE";

        public AliSmsSendRecordConsumer() {
            Task t = new Task(StartDeal);
            t.Start();

        }


        private void StartDeal() {
            try
            {
                if (this._consumer == null)
                {
                    var consumer = new Consumer
                    {
                        Topic = TOPIC,
                        //Group = GROUP,
                        NameServerAddress = App.Configuration["RocketMQ:NameServer"],

                        FromLastOffset = true,
                        //SkipOverStoredMsgCount = 0,
                        BatchSize = 10,//每次取的数量

                        //Log = XTrace.Log,
                    };

                    consumer.OnConsume = (q, ms) =>
                    {
                        Console.WriteLine("[{0}@{1}]收到消息[{2}]", q.BrokerName, q.QueueId, ms.Length);

                        foreach (var item in ms.ToList())
                        {
                            Console.WriteLine($"消息：主键【{item.Keys}】，" +
                                $"产生时间【{item.BornTimestamp.ToDateTime()}】，" +
                                $"内容【{item.Body.ToStr()}】");
                        }

                        return true;
                    };
                    //consumer.Configure(MqSetting.Current);
                    consumer.Start();
                    this._consumer = consumer;
                }

              
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }
        

    }
}
